﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using DevExpress.Web.ASPxEditors;
using DevExpress.Web.ASPxCallback;

namespace TireService.Website.UserControls
{
    public partial class ucAddCarData : System.Web.UI.UserControl
    {
        private int _carnumber;
        private int _subscriptionid;
        private string _primaryaddress;
        private string _secondaryaddress;

        public int CarNumber
        {
            get
            {
                return this._carnumber;
            }
            set
            {
                this._carnumber = value;
            }
        }

        public int SubscriptionId
        {
            get
            {
                return this._subscriptionid;
            }
            set
            {
                this._subscriptionid = value;
            }
        }

        public string PrimaryAddress
        {
            get
            {
                return this._primaryaddress;
            }
            set
            {
                this._primaryaddress = value;
            }
        }

        public string SecondaryAddress
        {
            get
            {
                return this._secondaryaddress;
            }
            set
            {
                this._secondaryaddress = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            //Reload();
        }

        public void LoadCar(CarData car)
        {
            txtRegistrationNumber.Text = car.RegistrationNumber;
            ddlCarBrand.Items.FindByValue(car.CarBrandId.ToString()).Selected = true;
            txtModel.Text = car.Model;
            txtEngineSize.Text = car.EngineSize;
            ddlFuelType.Items.FindByValue(car.FuelType.ToString()).Selected = true;
            ddlOtherTireSet.Items.FindByValue(car.OtherTireset.ToString()).Selected = true;
            ddlSelectAddress.SelectedIndex = -1;
            txtYear.Items.FindByValue(car.Year.ToString()).Selected = true;
            rblCurrentTireSet.SelectedIndex = car.CurrentTireset;
            cbLockingBolt.Checked = car.CurrentTiresetLockingbolts;
            cbLockingOtherTireSet.Checked = car.OtherTiresetLockingbolts;
            txtPickUpCustomerTireSetAddress.Text = car.PickupAddress;
            txtPickUpCustomerTireSetZipCode.Text = car.PickupZipCode;
            txtPickUpCustomerTireSetCity.Text = car.PickupCity;
            txtPickUpCustomerTireSetRemarkToAddress.Text = car.RemarksToPickupAddress;
            txtColor.Text = car.Color;

            if (car.OtherTireset == 1)
            {
                // Pickup tireset - change client side
                Page.ClientScript.RegisterStartupScript(this.GetType(), "ClientScriptSelectOtherTireSetAction", "OnSelectedTireSetActionChanged(this, " + car.OtherTireset.ToString() + ");", true);
            }
        }

        public void Reload(int CarCount)
        {
            // Hide add button to make it more simple for customer
            btnAddCar.Visible = !(CarCount == 1);

            TireServiceDB db = new TireServiceDB();

            lblCarNumber.Text = this.CarNumber.ToString();
            
            hfCarNumber.Value = this.CarNumber.ToString();

            lblSubscriptionDescription.Text = db.GetSubscriptionDescription(this.SubscriptionId);
            lblSubscriptionId.Text = this.SubscriptionId.ToString();

            // Get data for car brand dropdownlist
            ddlCarBrand.DataSource = db.GetCarBrand();
            ddlCarBrand.ValueField = "CarBrandId";
            ddlCarBrand.TextField = "Description";
            ddlCarBrand.DataBind();

            int TodayYear = DateTime.Now.Year;

            for (int i = TodayYear; i > 1990; i--)
            {
                ListEditItem item = new ListEditItem();
                item.Value = i;
                item.Text = i.ToString();
                txtYear.Items.Add(item);
            }

            string[] PrimaryAddress = this.PrimaryAddress.Split('|');
            string[] SecondaryAddress = this.SecondaryAddress.Split('|');

            //// Set primary address checkbox
            //rbPrimaryAddressTimeInterval.Items.Clear();
            //DevExpress.Web.ASPxEditors.ListEditItem itemPrimary = new DevExpress.Web.ASPxEditors.ListEditItem();
            //itemPrimary.Value = "true";
            //itemPrimary.Text = PrimaryAddress[0] + ", " + PrimaryAddress[1] + " " + PrimaryAddress[2];
            //rbPrimaryAddressTimeInterval.Items.Add(itemPrimary);

            //DevExpress.Web.ASPxEditors.ListEditItem itemSecondary = new DevExpress.Web.ASPxEditors.ListEditItem();
            //itemSecondary.Value = "false";
            //itemSecondary.Text = SecondaryAddress[0] + ", " + SecondaryAddress[1] + " " + SecondaryAddress[2];
            //rbPrimaryAddressTimeInterval.Items.Add(itemSecondary);

            // Show possible adresses to select from if tireset should be returned
            ddlSelectAddress.Items.Clear();
            string add1 = this.PrimaryAddress;
            string add2 = this.SecondaryAddress;
            string add3 = "-- Anden adresse --";

            ddlSelectAddress.Items.Add(add1, 0);
            ddlSelectAddress.Items.Add(add2, 1);
            ddlSelectAddress.Items.Add(add3, 2);

            // Clear form
            txtRegistrationNumber.Text = "";
            ddlCarBrand.SelectedIndex = -1;
            txtModel.Text = "";
            txtEngineSize.Text = "";
            ddlFuelType.SelectedIndex = -1;
            ddlOtherTireSet.SelectedIndex = -1;
            ddlSelectAddress.SelectedIndex = -1;
            rblCurrentTireSet.SelectedIndex = -1;
            cbLockingBolt.Checked = false;
            cbLockingOtherTireSet.Checked = false;
            txtPickUpCustomerTireSetAddress.Text = "";
            txtPickUpCustomerTireSetZipCode.Text = "";
            txtPickUpCustomerTireSetCity.Text = "";
            txtPickUpCustomerTireSetRemarkToAddress.Text = "";
            txtColor.Text = "";
            txtYear.SelectedIndex = -1;
        }

        /// <summary>
        /// Callback function that add car
        /// </summary>
        protected void callBackAddCar_Callback(object sender, CallbackEventArgs e)
        {
            try
            {
                // Get values from client
                // 0: Registrationnumber
                // 1: Car brand id
                // 2: Car model
                // 3: Enginesize
                // 4: Fueltype
                // 5: Year
                // 6: Color
                // 7: Currenttireset (0: Winter, 1: Summer)
                // 8: Locking bolts on current tireset (true/false)
                // 9: Othertireset (0: Get on first service, 1: Pick-up, 2: MBH has customer tires)
                // 10: Locking bolts on other tireset (true/false)
                // 11: Pickup address (optional)
                // 12: Pickup zipcode (optional)
                // 13: Pickup city (optional)
                // 14: Remarks to pickup address (optional)
                // 15: SubscriptionId
                string[] param = e.Parameter.Split('|');

                // Create new car
                CarData car = new CarData();
                
                // Add values to car
                car.CarNumber = Convert.ToInt32(hfCarNumber.Value);
                car.RegistrationNumber = param[0].ToString();
                car.CarBrandId = Convert.ToInt32(param[1]);
                car.Model = param[2].ToString();
                car.EngineSize = param[3].ToString();
                car.FuelType = Convert.ToInt32(param[4]);
                car.Year = Convert.ToInt32(param[5]);
                car.Color = param[6].ToString();
                car.CurrentTireset = Convert.ToInt32(param[7]);
                car.CurrentTiresetLockingbolts = Convert.ToBoolean(param[8]);
                car.OtherTireset = Convert.ToInt32(param[9]);
                car.OtherTiresetLockingbolts = Convert.ToBoolean(param[10]);
                car.PickupAddress = param[11].ToString();
                car.PickupZipCode = param[12].ToString();
                car.PickupCity = param[13].ToString();
                car.RemarksToPickupAddress = param[14].ToString();
                car.SubscriptionId = Convert.ToInt32(param[15]);

                List<CarData> cars = new List<CarData>();

                bool editmode = false;

                if (Session["CarList"] != null)
                {
                    cars = (List<CarData>)Session["CarList"];

                    CarData existingcar = cars.SingleOrDefault(p => p.RegistrationNumber == car.RegistrationNumber);

                    if (existingcar != null)
                    {
                        editmode = true; 
                        // Car already added once - remove it and add again
                        cars.Remove(existingcar);
                    }
                }
                
                // Add car to list
                cars.Add(car);

                // Update session
                Session["CarList"] = cars;

                // Return car number to client
                string result = Convert.ToInt32(hfCarNumber.Value).ToString();

                if (editmode)
                {
                    result += "|EditDone";
                }

                e.Result = result;
            }
            catch (Exception ex)
            {
                // Error
                throw new ArgumentException(ex.Message);
            }
        }

        public string GetCarNumber()
        {
            return this.CarNumber.ToString();
        }
    }
}